<?php

namespace Api\Model;
class ShopsModel extends BaseModel {

    /**
     * 添加个人入驻微店
     * @return int
     */
    public function addPerShop($userInfo) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = '数据添加失败!';
        $pshopId = I('shopId', 0);

        $data = array();
        $data['userId'] = $userInfo['userId'];
        $data['shopTel'] = I('phone');
        $data['areaId1'] = I('provinceId');
        $data['areaId2'] = I('cityId');
        $data['areaId3'] = I('districtId');
        $data['province'] = I('province');
        $data['city'] = I('city');
        $data['district'] = I('district');
        $data['shopAddress'] = I('address');
        $data['fullName'] = I('fullName');
        $address = $data['province'] . $data['city'] . $data['district'] . $data['shopAddress'];
        $lon = I('lon', '');
        $lat = I('lat', '');
        if ($lon && $lat) {
            $data['longitude'] = $lon;
            $data['latitude'] = $lat;
        } else {
            $ll = $this->getBaiduLonLat($address);
            $data['longitude'] = $ll['lon'];
            $data['latitude'] = $ll['lat'];
        }

        $m = M('shops');
        if ($pshopId == 0) {
            $isShop = $m->where(array('userId' => $userInfo['userId']))->getField('shopId');
            if ($isShop > 0) {
                $rt["code"] = 0;
                $rt['info'] = '您已经申请过微店!';
                return $rt;
            }
        }

        if (!preg_match("#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#", $data['shopTel'])) {
            $rt["code"] = 0;
            $rt['info'] = '手机号码格式错误!';
            return $rt;
        }
//        foreach ($data as $v) {
//            if ($v == '') {
//                $rt['code'] = 0;
//                $rt['info'] = '申请信息不完整!';
//                return $rt;
//            }
//        }

        if ($pshopId == 0) {
            $shopId = $m->add($data);
            $m->where('shopId=' . $shopId)->save(array('shopSN' => 100000 + $shopId, 'shopName' => (100000 + $shopId) . '号微店'));
        } else {
            $data['shopStatus'] = 0;
            $m->where('shopId=' . $pshopId)->save($data);
            $shopId = $pshopId;
        }

        $data['shopType'] = 2;
        $data['address'] = I('address');
        $data['phone'] = I('phone');
        $data['cardNum'] = I('cardNum');
        $data['cardImg'] = I('cardImg');
        $data['userCardImg'] = I('userCardImg');

        unset($data['shopTel']);
        unset($data['userId']);
        unset($data['shopAddress']);
        unset($data['shopStatus']);
        unset($data['longitude']);
        unset($data['latitude']);

        if ($pshopId == 0) {
            if (false !== $shopId) {
                $data['shopId'] = $shopId;
                $m = M('shops_auth');
                $authId = $m->add($data);
                if ($authId !== FALSE) {
                    $m = M('users');
                    $m->where(array('userId' => $userInfo['userId']))->save(array('userType' => 2));
                    $rt['code'] = 1;
                    $rt['info'] = '数据添加成功!';
                }
                return $rt;
            }
        } else {
            $m = M('shops_auth');
            $authId = $m->where('shopId=' . $pshopId)->save($data);
            $rt['code'] = 1;
            $rt['info'] = '数据添加成功!';
            return $rt;
        }

        return $rt;
    }

    /**
     * 添加商家入驻微店
     * @return int
     */
    public function addCompShop($userInfo) {
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = '数据添加失败!';
        $pshopId = I('shopId', 0);

        $data = array();
        $data['userId'] = $userInfo['userId'];
        $data['shopTel'] = I('phone');
        $data['areaId1'] = I('provinceId');
        $data['areaId2'] = I('cityId');
        $data['areaId3'] = I('districtId');
        $data['province'] = I('province');
        $data['city'] = I('city');
        $data['district'] = I('district');
        $data['shopAddress'] = I('address');
        $data['fullName'] = I('fullName');
        $address = $data['province'] . $data['city'] . $data['district'] . $data['shopAddress'];
        $ll = $this->getBaiduLonLat($address);
        $data['longitude'] = $ll['lon'];
        $data['latitude'] = $ll['lat'];

        $m = M('shops');
        if ($pshopId == 0) {
            $isShop = $m->where(array('userId' => $userInfo['userId']))->getField('shopId');
            if ($isShop > 0) {
                $rt["code"] = 0;
                $rt['info'] = '您已经申请过微店!';
                return $rt;
            }
        }

        if (!preg_match("#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#", $data['shopTel'])) {
            $rt["code"] = 0;
            $rt['info'] = '手机号码格式错误!';
            return $rt;
        }
//        foreach ($data as $v) {
//            if ($v == '') {
//                $rt['code'] = 0;
//                $rt['info'] = '申请信息不完整!';
//                return $rt;
//            }
//        }

        if ($pshopId == 0) {
            $shopId = $m->add($data);
            $m->where('shopId=' . $shopId)->save(array('shopSN' => 100000 + $shopId, 'shopName' => (100000 + $shopId) . '号微店'));
        } else {
            $data['shopStatus'] = 0;
            $m->where('shopId=' . $pshopId)->save($data);
            $shopId = $pshopId;
        }

        $data['shopType'] = 1;
        $data['address'] = I('address');
        $data['phone'] = I('phone');
        $data['company'] = I('company');
        $data['companyNum'] = I('companyNum');
        $data['companyImg'] = I('companyImg');
        $data['companyAddress'] = I('companyAddress');

        unset($data['shopTel']);
        unset($data['userId']);
        unset($data['shopAddress']);
        unset($data['shopStatus']);
        unset($data['longitude']);
        unset($data['latitude']);

        if ($pshopId == 0) {
            if (false !== $shopId) {
                $data['shopId'] = $shopId;
                $m = M('shops_auth');
                $authId = $m->add($data);
                if ($authId !== FALSE) {
                    $m = M('users');
                    $m->where(array('userId' => $userInfo['userId']))->save(array('userType' => 1));

                    $rt['code'] = 1;
                    $rt['info'] = '数据添加成功!';
                }

                return $rt;
            }
        } else {
            $m = M('shops_auth');
            $authId = $m->where('shopId=' . $pshopId)->save($data);
            $rt['code'] = 1;
            $rt['info'] = '数据添加成功!';
            return $rt;
        }

        return $rt;
    }

    /**
     * 获取店铺验证信息
     * @param type $useInfo
     */
    public function getShopAuth($userInfo) {
        $m = M('shops_auth');
        $shopId = M('shops')->where('userId=' . $userInfo['userId'])->getField('shopId');
        $data = $m->where('shopId=' . $shopId)->find();
        $data['cardImg'] = json_decode(htmlspecialchars_decode($data['cardImg']));

        return $data;
    }

    /**
     * 获取店铺基本信息
     */
    public function getShopConfig($userInfo) {
        $m = M('shops');
        $shop = $m->where('userId=' . $userInfo['userId'])->field('shopId,userId,shopName,shopImg,shopTel,shopAddress,templateId,depositId,depositMoney,listStyle,areaId1,areaId2,areaId3,postage,province,city,district,openResale,shopStatus')->find();
        $shop['depositId'] = intval($shop['depositId']);
        $shop['shopSN'] = 100000 + $shop['shopId'];
        $shop['deposit'] = M('shops_deposit')->where('id=' . $shop['depositId'])->find();
        $shop['shopUrl'] = C('WEB_URL') . U('Wap/shopsIndex/newGoodsList/shopId/' . $shop['shopId']);
        $shop['shopQrcode'] = 'http://qr.topscan.com/api.php?text=' . $shop['shopUrl'];

        return $shop;
    }

    /**
     * 获取发布的商品
     */
    public function getGoodsList() {
        $m = M('goods');
        $shopId = I('shopId');
        $num = I('num') ? I('num') : 5;
        $page = I('page') ? I('page') : 1;
        $page = ($page - 1) * $num;
        $rs = $m->where('shopId=' . $shopId . ' and isSource = 1 and isDel = 0')->field('goodsId,goodsName,goodsName,marketPrice, shopPrice,goodsSize,goodsWeight,goodsStatus,goodsThumbs,isSelling,isSale,goodsStock, goodsStatus')->order('goodsId DESC,goodsStock DESC,  goodsFlag DESC')->limit($page, $num)->select();
        $goodsList = array();
        foreach ($rs as $v) {
            $v['pics'] = M('goods_gallerys')->where('goodsId=' . $v['goodsId'])->field('id,goodsImg,goodsThumbs')->select();
            $v['wapUrl'] = C('WEB_URL') . U('Wap/Index/goodsDetail/id/' . $v['goodsId']);
            $goodsList[] = $v;
        }

        return $goodsList;
    }

    /**
     * 获取转售的商品
     */
    public function getResalesList() {
        $m = M('goods');
        $shopId = I('shopId');
        $num = I('num') ? I('num') : 5;
        $page = I('page') ? I('page') : 1;
        $page = ($page - 1) * $num;
      //  $rs = $m->where('shopId=' . $shopId . ' and isSource = 0 and isDel = 0 and goodsFlag = 1 and isSale = 1')->field('goodsId,goodsName,goodsName,marketPrice, shopPrice,goodsSize,goodsWeight,goodsStatus,goodsThumbs,isSelling,isSale,goodsStock,goodsStatus')->order('goodsStock DESC, goodsId DESC')->limit($page, $num)->select();
        $rs = $m->where('shopId=' . $shopId . ' and isSource = 0 and isDel = 0 and goodsFlag = 1 and isSale = 1')->field('goodsId,goodsName,goodsName,marketPrice, shopPrice,goodsSize,goodsWeight,goodsStatus,goodsThumbs,isSelling,isSale,goodsStock,goodsStatus')->order('goodsId DESC')->limit($page, $num)->select();

        $goodsList = array();
        foreach ($rs as $v) {
            $v['pics'] = M('goods_gallerys')->where('goodsId=' . $v['goodsId'])->field('id,goodsImg,goodsThumbs')->select();
            $v['wapUrl'] = C('WEB_URL') . U('Wap/Index/goodsDetail/id/' . $v['goodsId']);
            $goodsList[] = $v;
        }


        return $goodsList;
    }

    /**
     * 保证金支付记录
     * @param type $userId
     * @return type
     */
    public function depositMoney($userId) {
        $m = M('user_deposit_log');
        $rt = array();
        $rt['code'] = 0;
        $rt['info'] = 'Error!';

        $data = array();
        $data['userId'] = $userId;
        $data['orderSN'] = substr(time(), 2);
        $data['priceSum'] = I('price');
        $data['depositId'] = I('depositId');
        $data['type'] = 2;
        $data['payType'] = I('payType');
        $data['time'] = date('Y-m-d H:i:s');

        if ($data['payType'] == 1) {
            $balance = M('users')->where('userId=' . $userId)->getField('userBalance');
            if ($balance < $data['priceSum']) {
                $rt['info'] = '账户余额不足!';
                return $rt;
            }
        }

        if ($data['payType'] == 1) {
            $rs = M('users')->where('userId=' . $userId)->setDec('userBalance', $data['priceSum']);
            if (!$rs) {
                $rt['info'] = '余额支付失败!';
                return $rt;
            }
            $m = M('shops');
            $m->where('userId=' . $userId)->save(array('depositId' => $data['depositId']));
            $m->where('userId=' . $userId)->setInc('depositMoney', $data['priceSum']);
            $this->MlogBalance($userId, $data['priceSum'], 1, '保证金支付');
            $rt['code'] = 1;
            $rt['info'] = '支付成功!';
            $rt['data'] = $data;
            return $rt;
        }

        $rs = $m->add($data);
        if ($rs == FALSE)
            return $rt;

        $rt['code'] = 1;
        $rt['info'] = 'Success!';
        $rt['data'] = $data;
        return $rt;
    }

    /**
     * 好友商家
     */
    public function shopFriend($userId) {
        $sql = 'SELECT f.id,u.userName,u.rongToken,u.userId,ifnull(u.userPhoto,"") userPhoto,ifnull(s.shopName,"") shopName,ifnull(s.shopId, 0) shopId,ifnull((s.shopId + 100000), 0) shopSn, ifnull(s.shopImg,"") shopImg, f.isResale '
                . ' FROM __PREFIX__user_friends as f '
                . ' LEFT JOIN __PREFIX__users as u ON f.uid = u.userId '
                . ' LEFT JOIN __PREFIX__shops as s ON f.uid = s.userId '
                . ' WHERE u.userType > 0 AND f.type = 2 AND f.fuid = ' . $userId;
        $data = $this->query($sql);

        return $data;
    }

    /**
     * 设置是否同意好友转售
     */
    public function setResale($userId) {
        $m = M('user_friends');
        $fuid = I('userId', 0);
        $isResale = I('isResale', 0);
        if ($fuid == 0)
            return FALSE;
        $m->isResale = $isResale;
        $rs = $m->where('uid=' . $fuid . ' and fuid=' . $userId)->save();

        return $rs;
    }

}